package com.test.sdk.core.service.impl;

import com.test.sdk.common.pojo.OnlineUser;
import com.test.sdk.common.pojo.User;
import com.test.sdk.common.util.ErrorConstants;
import com.test.sdk.common.util.ResponseTO;
import com.test.sdk.common.util.SignUtil;
import com.test.sdk.core.dao.OnlineUserDAO;
import com.test.sdk.core.dao.UserDAO;
import com.test.sdk.core.exception.SdkException;
import com.test.sdk.core.service.RedisService;
import com.test.sdk.core.service.UserService;
import com.test.sdk.core.util.AccountUtil;
import com.test.sdk.core.util.SdkConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 徒有琴
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * @param mobile  手机号
     * @param isExist 手机号是否注册过
     * @return
     */
//    @Value("${sdk.redis.setex}")
//    private String SETEX;

    @Autowired
    private RedisService redisService;

    @Override
    public boolean doSendShortMessage(String mobile, boolean isExist) throws SdkException {
        Integer userId = userDAO.getUserIdByNum(mobile);
        if (isExist && userId == null) {//要求注册过,但实际上没注册
            throw new SdkException(ErrorConstants.ACCOUNT_NOT_EXIST);
        }
        if (!isExist && userId != null) {//要求没注册过,但实际上注册了
            throw new SdkException(ErrorConstants.ACCOUNT_ALREADY_EXIST);
        }
        //
        String randomCode = AccountUtil.getRandomNum(6);
        System.out.println(randomCode);
//        String url = "http://v.juhe.cn/sms/send?mobile=" + mobile + "&tpl_id=" + SdkConstants.SHORT_MSG_TPL_ID + "&tpl_value=%23code%23%3D" + randomCode + "&key=" + SdkConstants.SHORT_MSG_APPKEY;
//        Map<String, Object> result = restTemplate.getForObject(url, HashMap.class);
//        System.out.println(result);
//        if (result != null && "0".equals(result.get("error_code").toString())) {
//            return true;
//        }

        redisService.setex(mobile, randomCode, SdkConstants.MOBILE_VERCODE_TIMEOUT * 100);
        return false;
    }

    @Override
    public User doMobileRegist(String mobile, String code, Integer channelId) throws SdkException {
        //检验验证码
        ResponseTO redisCode = redisService.get(mobile);//查询验证码
        //redis服务失效、请求出现异常、没查到结果(手机号错了，或者过期了)、验证码不相等
        if (redisCode == null || !redisCode.isSuccess() || redisCode.getResult() == null || !code.equals(redisCode.getResult().toString())) {
            throw new SdkException(ErrorConstants.PARAM_ERROR);
        }
        //delete redis中的验证码，当作业

        Integer userId = userDAO.getUserIdByNum(mobile);
        if (userId == null) {
            User user = new User();
            user.setChannelId(channelId);
            user.setNum(mobile);
            user.setRegistDate(new Date());
            user.setUserType(SdkConstants.USER_TYPE_BIND);
            user.setPassword("");
            userDAO.addUser(user);
            userDAO.addUserNum(user);
            userDAO.addUserDynamic(user.getId());
            return user;
        } else {
            throw new SdkException(ErrorConstants.PHONE_ALREADY_EXIST);
        }
    }

    @Override
    public User doUsernameRegist(String name, String password, Integer channelId) throws SdkException {
        Integer userId = userDAO.getUserIdByName(name);
        if (userId == null) {
            User user = new User();
            user.setChannelId(channelId);
            user.setName(name);
            user.setRegistDate(new Date());
            user.setUserType(SdkConstants.USER_TYPE_BIND);
            user.setPassword(SignUtil.md5(password + SdkConstants.DEFAULT_PASSWORD_SALT));
            userDAO.addUser(user);
            userDAO.addUserName(user);
            userDAO.addUserDynamic(user.getId());
            return user;
        } else {
            throw new SdkException(ErrorConstants.USERNAME_ALREADY_EXIST);
        }
    }

    @Autowired
    private OnlineUserDAO onlineUserDAO;

    @Override
    public String doUsernameLogin(String name, String password, Integer gameId) throws SdkException {
        Integer userId = userDAO.getUserIdByName(name);
        if (userId == null) {
            throw new SdkException(ErrorConstants.USERNAME_NOT_EXIST);
        }
        User user = userDAO.getUserById(userId);
        if (!user.getPassword().equals(SignUtil.md5(password + SdkConstants.DEFAULT_PASSWORD_SALT))) {
            throw new SdkException(ErrorConstants.ACCOUNT_PASSWORD_ERROR);
        }
        String ticket = SignUtil.md5(System.currentTimeMillis() + password + userId);
        OnlineUser onlineUser = new OnlineUser();
        onlineUser.setLastAct(new Date());
        onlineUser.setTicket(ticket);
        onlineUser.setGameId(gameId);
        onlineUser.setLoginAccount(name);
        onlineUser.setUserId(userId);
        onlineUser.setLoginDate(new Date());
        onlineUserDAO.deleteOnlineUser(userId);
        onlineUserDAO.addOnlineUser(onlineUser);
        redisService.setex(ticket, userId.toString(), SdkConstants.LOGIN_TIMEOUT);
        return ticket;
    }

    @Override
    public void heartBeat(String ticket) {
        redisService.expire(ticket,SdkConstants.LOGIN_TIMEOUT);
        onlineUserDAO.updateLastAct(ticket);
    }
}
